package cn.jsj.invite.service.impl;

import cn.jsj.invite.dao.EnterpriseDao;
import cn.jsj.invite.dao.SchoolDao;
import cn.jsj.invite.dao.StudentDao;
import cn.jsj.invite.dao.UserDao;
import cn.jsj.invite.exception.CustomException;
import cn.jsj.invite.interceptor.TokenCensor;
import cn.jsj.invite.pojo.UserEnt;
import cn.jsj.invite.pojo.identity.UserIdentityEnum;
import cn.jsj.invite.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author 卢斌
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserDao userDao;
    private final TokenCensor tokenCensor;
    private final StudentDao studentDao;
    private final EnterpriseDao enterpriseDao;
    private final SchoolDao schoolDao;

    @Autowired
    public UserServiceImpl(UserDao userDao, TokenCensor tokenCensor, StudentDao studentDao, EnterpriseDao enterpriseDao, SchoolDao schoolDao) {
        this.userDao = userDao;
        this.tokenCensor = tokenCensor;
        this.studentDao = studentDao;
        this.enterpriseDao = enterpriseDao;
        this.schoolDao = schoolDao;
    }


    @Override
    public UserEnt userLogin(String account, UserIdentityEnum userIdentity, String password) {
        UserEnt userLoginInfo;
        switch (userIdentity) {
            case STUDENT:
                userLoginInfo = userDao.getStudentEntByAccount(account);
                break;
            case ENTERPRISE:
                userLoginInfo = userDao.getEnterpriseEntByAccount(account);
                break;
            case SCHOOL:
                userLoginInfo = userDao.getSchoolAdminEntByAccount(account);
                break;
            default:
                throw new CustomException("无效的用户类型");
        }
        if (userLoginInfo == null || !userLoginInfo.getPassword().equals(password)) {
            throw new CustomException("请检查您输入的账号密码");
        }
        userLoginInfo = getUserDetailInfoById(userLoginInfo.getId(), userLoginInfo.getUserIdentity());
        String tokenValue = tokenCensor.tokenIssue(userLoginInfo.getId(), userLoginInfo.getUserIdentity());
        userLoginInfo.setPassword(tokenValue);
        return userLoginInfo;
    }

    /**
     * Id获取用户信息
     *
     * @param id           用户Id
     * @param userIdentity 用户身份标识
     * @return 用户详细信息
     */
    @Override
    public UserEnt getUserDetailInfoById(Long id, UserIdentityEnum userIdentity) {
        switch (userIdentity) {
            case STUDENT:
                return studentDao.selectStudentById(id);
            case ENTERPRISE:
                return enterpriseDao.selectEnterpriseById(id);
            case SCHOOL:
                return schoolDao.selectSchoolAdminById(id);
            default:
                throw new CustomException("无效的用户类型");
        }
    }
}
